window.onload = function(){
  $('.loading-overlay').hide();
};
$(function(){
  //初始化fastclick
  FastClick.attach(document.body);

  //抽奖
  !function(){
    var rem = 100*(document.documentElement.getBoundingClientRect().width/750);
    var canvasWidth = 7.5*rem;
    var canvasHeight = 5.6*rem;
    var ball_count = 3;//小球的个数
    var circle_x = 0;//圆心的X坐标
    var circle_y = 0;//圆心的Y坐标
    var circle_a = 2.6*rem;//椭圆长轴
    var circle_b = .6*rem;//椭圆短轴
    var now_count = 0;//当前显示小球的个数
    var balls_array;//用来存储小球信息
    var angle_change = 1;//角度变化
    var timer;
    var canvas;//画布
    var ctx;//画布环境
    var running = false;
    var giftBg = new Image();
    giftBg.src = 'image/egg2.png';
    var finalEgg = new Image();
    finalEgg.src = 'image/egg3.png';
    var hitMusic = document.getElementById('hitAudio');
    var hitCount;

    //获取抽奖次数
    $.get('/api/lotteryCount', function(data){
      hitCount = data.count;
      $('.count-text').text(hitCount);
      if(!hitCount){
        getMyAwards();
      }
    })
    //我的中奖记录
    function getMyAwards() {
      $.get('/api/myAwards', function(data){
        if(data.results && data.results.length>0){
          var record = data.results[0];
          $('.myprize-box').html('您于<span>'+fmtTime(record.createdAt)+'</span>抽到<span>'+(record.award === 1 ? '一等奖':(record.award === 2 ? '二等奖' : '三等奖'))+'</span>编号:<span>'+record.shortId+'</span><span class="'+(record.finished ? "received myprize-status" : "myprize-status")+'">'+(record.finished ? "已领取" : "未领取")+'</span>').show();
        }
      })
    }
    //所有的中奖记录
    var mockList = [
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 2,
        "shortId": "453695",
        "nick": '夏弘威',
        "owner": "xiahwei",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 2,
        "shortId": "453695",
        "nick": '李弘基',
        "owner": "8lihonji",
        "_v": 0,
        "finished": false
      },

      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505520000000",
        "award": 3,
        "shortId": "453695",
        "nick": '魏唯一',
        "owner": "weiweiyi6",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505520000000",
        "award": 3,
        "shortId": "453695",
        "nick": '季布',
        "owner": "jibu26",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505520000000",
        "award": 3,
        "shortId": "453695",
        "nick": '欧阳林',
        "owner": "6ouylin",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505520000000",
        "award": 3,
        "shortId": "453695",
        "nick": '夏曜',
        "owner": "xiayao",
        "_v": 0,
        "finished": false
      },

      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505606400000",
        "award": 3,
        "shortId": "453695",
        "nick": '伟杰赵',
        "owner": "liweijie",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505606400000",
        "award": 3,
        "shortId": "453695",
        "nick": '秋水',
        "owner": "qiushui",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505606400000",
        "award": 3,
        "shortId": "453695",
        "nick": '十七',
        "owner": "3liweijie",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505606400000",
        "award": 3,
        "shortId": "453695",
        "nick": '十七',
        "owner": "zhaoyn",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505606400000",
        "award": 2,
        "shortId": "453695",
        "nick": '小红',
        "owner": "xiaohong",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505606400000",
        "award": 2,
        "shortId": "453695",
        "nick": '小红',
        "owner": "2xiaohong",
        "_v": 0,
        "finished": false
      },

      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505692800000",
        "award": 3,
        "shortId": "453695",
        "nick": '赵美美',
        "owner": "99meimei",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505692800000",
        "award": 3,
        "shortId": "453695",
        "nick": '袁茹',
        "owner": "4yuanru4",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505692800000",
        "award": 2,
        "shortId": "453695",
        "nick": '十八',
        "owner": "haozi",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505692800000",
        "award": 2,
        "shortId": "453695",
        "nick": '十八two',
        "owner": "88dong",
        "_v": 0,
        "finished": false
      },

      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505779200000",
        "award": 3,
        "shortId": "453695",
        "nick": '李珍',
        "owner": "caoxia6",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505779200000",
        "award": 3,
        "shortId": "453695",
        "nick": '李珍',
        "owner": "xumimi",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505779200000",
        "award": 3,
        "shortId": "453695",
        "nick": "十九",
        "owner": "1caoxia6",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505779200000",
        "award": 3,
        "shortId": "453695",
        "nick": '李珍',
        "owner": "niuniu",
        "_v": 0,
        "finished": false
      },

      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505865600000",
        "award": 2,
        "shortId": "453695",
        "nick": '二十',
        "owner": "xuxia",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505865600000",
        "award": 2,
        "shortId": "453695",
        "nick": '二十',
        "owner": "luban78",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505865600000",
        "award": 1,
        "shortId": "453695",
        "nick": '二十',
        "owner": "23xumo",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505865600000",
        "award": 1,
        "shortId": "453695",
        "nick": '马良',
        "owner": "maliang6",
        "_v": 0,
        "finished": false
      },

      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505952000000",
        "award": 2,
        "shortId": "453695",
        "nick": '二十一',
        "owner": "wangjyun",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505952000000",
        "award": 2,
        "shortId": "453695",
        "nick": '二十一',
        "owner": "8liudong",
        "_v": 0,
        "finished": false
      },

      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505952000000",
        "award": 3,
        "shortId": "453695",
        "nick": '二十一',
        "owner": "6wangjyun",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505952000000",
        "award": 3,
        "shortId": "453695",
        "nick": '二十一',
        "owner": "liudong9",
        "_v": 0,
        "finished": false
      },

      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1506038400000",
        "award": 1,
        "shortId": "453695",
        "nick": '袁茹',
        "owner": "yuanru",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1506038400000",
        "award": 1,
        "shortId": "453695",
        "nick": '李珍',
        "owner": "7lizhen",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1506038400000",
        "award": 2,
        "shortId": "453695",
        "nick": '袁茹',
        "owner": "erer",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1506038400000",
        "award": 2,
        "shortId": "453695",
        "nick": '李珍',
        "owner": "8lizhen",
        "_v": 0,
        "finished": false
      },
    ]
    $.get('/api/awards',function(data){
      var list = data.results.concat(mockList);
      var listHtml = '';
      if(list.length === 0){
        $('#winnerList').parents('.winner-list-container').hide();
      }else{
        for(var i=0; i<list.length; i++){
          list[i].owner = list[i].owner.replace(/^(.{1})(.*)(.{1})$/g, function(a, b, c, d) {
            return b + c.replace(/./g, "*") + d;
          });
          listHtml+='<li><span>'+list[i].owner+'</span><span>'+(list[i].award === 1 ? '一等奖':(list[i].award === 2 ? '二等奖' : '三等奖')) +'</span><span>'+fmtTime(list[i].createdAt)+'</span></li>'
        }
        $('#winnerList').html(listHtml);
        marquee();
      }
    })
    //所有的中奖记录(假数据)
    /*
    var list = [
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 1,
        "shortId": "453695",
        "nick": '夏弘威',
        "owner": "xiahongwei",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 3,
        "shortId": "453695",
        "nick": '李弘基',
        "owner": "lihongji",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 3,
        "shortId": "453695",
        "nick": '魏唯一',
        "owner": "weiweiyi",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 2,
        "shortId": "453695",
        "nick": '季布',
        "owner": "jibu",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 3,
        "shortId": "453695",
        "nick": '欧阳林',
        "owner": "ouyanglin",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 1,
        "shortId": "453695",
        "nick": '夏曜',
        "owner": "xiayao",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 3,
        "shortId": "453695",
        "nick": '伟杰赵',
        "owner": "liweijie",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 3,
        "shortId": "453695",
        "nick": '秋水',
        "owner": "qiushui",
        "_v": 0,
        "finished": false
      },
      {
        "_id":"59874abhaf68546455632",
        "createdAt": "1505440800000",
        "award": 3,
        "shortId": "453695",
        "nick": '小红',
        "owner": "xiaohong",
        "_v": 0,
        "finished": false
      }
    ];
    var list = [];
    var listHtml = '';
    if(list.length===0){
      $('#winnerList').parents('.winner-list-container').hide();
    }else{
      for(var i=0; i<list.length; i++){
        list[i].owner = list[i].owner.replace(/^(.{1})(.*)(.{1})$/g, function(a, b, c, d) {
          return b + c.replace(/./g, "*") + d;
        });
        listHtml+='<li><span>'+list[i].owner+'</span><span>'+(list[i].award === 1 ? '一等奖':(list[i].award === 2 ? '二等奖' : '三等奖')) +'</span><span>'+fmtTime(list[i].createdAt)+'</span></li>'
      }
      $('#winnerList').html(listHtml);
      marquee();
    }
    */
    canvas = document.getElementById('myCanvas');
    canvas.addEventListener('click', clickCanvas, false);
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    ctx = canvas.getContext('2d');
    balls_array = new Array(ball_count);
    circle_x =  canvasWidth/ 2;
    circle_y = canvasHeight / 2;
    loadBall();

    $('.close-btn').click(function(){
      $('.count-text').text(hitCount);
      getMyAwards();
      $('#resultPop').hide();
      running = true;
      timer = setInterval(ballMove, 40);
    });
    //小球移动
    function ballMove() {
      ctx.clearRect(0, 0, canvasWidth, canvasHeight);
      var len = balls_array.length;
      for (var i = 0; i < len; i++) {
        var ball = balls_array[i];
        if (ball.angle == 360) {
          ball.angle = 0;
        }
        ball.angle = ball.angle + angle_change;//角度
        var radian = ball.angle * (Math.PI / 180);//弧度
        ball.x = (circle_x + circle_a * Math.cos(radian)) - ball.w / 2;
        ball.y = (circle_y + circle_b * Math.sin(radian)) - ball.h / 2;
      };
      //调整先后顺序，解决zIndex层级
      var temp, flag;
      for(var k=len-1; k>0; k--){
        flag = 0;
        for(var j=1; j<=k; j++){
          if(balls_array[j].angle > balls_array[j-1].angle){
            temp = balls_array[j];
            balls_array[j] = balls_array[j-1];
            balls_array[j-1] = temp;
            flag = 1;
          }
        }
        if(flag == 0){
          break;
        }
      };
      for(var m=0; m<len; m++){
        var ball = balls_array[m];
        var num = setProp(ball, 0.8, 1);
        ctx.drawImage(ball.image, ball.x, ball.y, ball.w * num, ball.h * num);
      }
    }
    //加载小球
    function loadBall() {
      for (var i = 0; i < ball_count; i++) {
        var angle = (i + 1) * (360 / ball_count);//角度
        var radian = angle * (Math.PI / 180);//弧度
        //初始化图片
        var img = new Image()
        img.id = i + 1;
        img.src = 'image/egg.png';
        //存放小球信息
        var ball = {};
        ball.id = img.id;
        ball.w = 1.8*rem;
        ball.h = 2.3*rem;
        ball.x = (circle_x + circle_a * Math.cos(radian)) - ball.w / 2;
        ball.y = (circle_y + circle_b * Math.sin(radian)) - ball.h / 2;
        ball.angle = angle;
        ball.image = img;
        balls_array[i] = ball;
        img.onload = function () {
          for (var j = 0; j < balls_array.length; j++) {
            if (this.id == balls_array[j].id) {
              var item = balls_array[j];
              var num = setProp(item, 0.8, 1);
              ctx.drawImage(img, item.x, item.y, item.w * num, item.h * num);
              break;
            }
          };
          now_count++;
          if (now_count == ball_count) {//当小球全部加载完成
            timer = setInterval(ballMove, 40);//40ms移动小球
            running = true;
          }
        }
      }
    }
    //鼠标单击canvas
    function clickCanvas(e) {
      p = getEventPosition(e);
      var idx;
      for (var i = 0; i < balls_array.length; i++) {
        var ball = balls_array[i];
        if (p.x >= ball.x && p.x <= (ball.x + ball.w) && p.y >= ball.y && p.y <= (ball.y + ball.h) && running ) {
          //模拟拿到的后台数据
          if(hitCount>0){
            clearInterval(timer);
            running = false;
            hitCount>0 && hitCount--;
            var rate = setProp(ball, 0.8, 1);
            $('#hit').show().css({'width': 1.6*rem*rate+'px','height': 1.6*rem*rate+'px','left': ball.x+35+'px','top': ball.y-40+'px'}).addClass('on');
            hitMusic.play();
          }
          var award;
          $.ajax({
            type: 'post',
            url: '/api/lottery',
            data: {index: parseInt(ball.id)},
            success: function(data){
              if(data.award){
                award = data.award;
                switch (award) {
                  case 1:
                    $('#giftImg img').attr('src','image/first.png');
                    $('#resultPop .gift-box').children('img').attr('src','image/first-gift.png');
                    $('#resultPop .result').text('一等奖');
                    break;
                  case 2:
                    $('#giftImg img').attr('src','image/second.png');
                    $('#resultPop .gift-box').children('img').attr('src','image/second-gift.png');
                    $('#resultPop .result').text('二等奖');
                    break;
                  case 3:
                    $('#giftImg img').attr('src','image/third.png');
                    $('#resultPop .gift-box').children('img').attr('src','image/third-gift.png');
                    $('#resultPop .result').text('三等奖');
                    break;
                }
                idx = ball.id;
                setTimeout(function(){
                  $('#hit').removeClass('on').hide();
                  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                  for(var j=0; j<balls_array.length; j++){
                    var ball = balls_array[j];
                    var num = setProp(ball, 0.8, 1);
                    if(ball.id === idx){
                      ctx.drawImage(giftBg, ball.x-40, ball.y-62, ball.w*num+80, ball.h*num+62);
                      $('#giftImg').show().css({'width': 1.6*rem*num+'px','height': 1.6*rem*num+'px','left': ball.x+8+'px','top': ball.y-20+'px'}).addClass('on');
                    }else{
                      ctx.drawImage(ball.image, ball.x, ball.y, ball.w * num, ball.h * num);
                    }
                  };
                  $('#giftImg img').show();
                },400)
                setTimeout(function(){
                  $('#resultPop').show();
                  $('#giftImg').removeClass('on').hide();
                  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                  for(var i=0; i<balls_array.length; i++){
                    var ball = balls_array[i];
                    var num = setProp(ball, 0.8, 1);
                    if(ball.id === idx){
                      ctx.drawImage(finalEgg, ball.x, ball.y, ball.w*num, ball.h*num);
                    }else{
                      ctx.drawImage(ball.image, ball.x, ball.y, ball.w*num, ball.h*num);
                    }
                  }
                },1200)
              }else if(data.error){
                $('.layer-toast').children('.layer-content').text(data.error).end().show();
                setTimeout(function(){
                  $('.layer-toast').hide();
                },1500);
              }
            },
            error: function(error){}
          })
          break;
        }
      }
    }
    //获取事件对象发生的位置
    function getEventPosition(ev) {
      var x, y;
      if (ev.layerX || ev.layerX == 0) {
        x = ev.layerX;
        y = ev.layerY;
      } else if (ev.offsetX || ev.offsetX == 0) {
        x = ev.offsetX;
        y = ev.offsetY;
      }
      return { x: x, y: y };
    }
    //把Y坐标转化为透明度和尺寸属性，范围在n1到n2之间;
    function setProp(ball, n1, n2) {
      return (((ball.y + ball.h / 2 - circle_y) + 2 * circle_b) / circle_b - 1) / 2 * (n2 - n1) + n1;
    }
    //跑马灯效果
    function marquee(){
      var $marqueeDom = $('#winnerList');
      var $marqueeContainer = $marqueeDom.parent();
      var marqueeContainerHeight = $marqueeContainer.height();
      var marqueeHeight = $marqueeDom.height();
      var multipleRate = Math.round(marqueeHeight/marqueeContainerHeight);
      if(marqueeHeight>marqueeContainerHeight){
        var clone = $marqueeDom.clone().addClass('clone').removeAttr('id');
        $marqueeContainer.append(clone);
        $('.winner-list').css({ 'animation': 'marquee '+multipleRate*10+'s linear infinite', '-webkit-animation': 'marquee '+multipleRate*10+'s linear infinite'});
      }
    }
    //格式化时间
    function fmtTime(time){
      return new Date(parseInt(time)).toLocaleString().split(' ')[0].replace(/[-]/g,'.');
    }
  }()

  //音乐播放
  var bgMusic = document.getElementById('backgroundAudio');
  $('#musicBtn').click(function(){
    if(bgMusic.paused){
      bgMusic.play();
      $(this).addClass('on').removeClass('off');
    }else{
      bgMusic.pause();
      $(this).addClass('off').removeClass('on');
    }
  });
})